from colorsys import hsv_to_rgb
import numpy as np
from bokeh.models import DataTable, TableColumn, NumberEditor, NumberFormatter, Div, HTMLTemplateFormatter
from bokeh.layouts import column

def generate_colors(n):
    """生成N个唯一颜色（HSV色环均匀采样）"""
    return [f"#{int(hsv_to_rgb(i/n,1,1)[0]*255):02x}"
            f"{int(hsv_to_rgb(i/n,1,1)[1]*255):02x}"
            f"{int(hsv_to_rgb(i/n,1,1)[2]*255):02x}" 
            for i in range(n)]

def validate_coordinates(arr):
    """坐标数据验证"""
    arr = np.asarray(arr)
    if arr.ndim != 2 or arr.shape[1] != 2:
        raise ValueError("输入必须为Nx2的二维数组")
    return arr

def edges_to_bokeh(edges):
    """将边列表转换为Bokeh兼容格式"""
    xs, ys = [], []
    for edge in edges:
        xs.append([edge[0], edge[2]])
        ys.append([edge[1], edge[3]])
    return {'xs': xs, 'ys': ys}

def create_editable_table(source, title_text):
    """创建可编辑表格（修复样式参数）"""
    color_template = """
    <div style="background:<%= value %>; 
                width: 24px; 
                height: 24px;
                border-radius: 4px;
                border: 1px solid #666;
                box-shadow: 1px 1px 3px rgba(0,0,0,0.2)">
    </div>
    """
    
    columns = [
        TableColumn(
            field="color_hex", 
            title="颜色",
            width=70,
            formatter=HTMLTemplateFormatter(template=color_template)
        ),
        TableColumn(
            field="x", 
            title="X坐标",
            editor=NumberEditor(),
            formatter=NumberFormatter(format="0.000"),
            width=110
        ),
        TableColumn(
            field="y", 
            title="Y坐标",
            editor=NumberEditor(),
            formatter=NumberFormatter(format="0.000"),
            width=110
        )
    ]
    
    return column(
        Div(text=f"<b style='font-size:14px'>{title_text}</b>", 
           styles={'margin-bottom': '10px'}),
        DataTable(
            source=source,
            columns=columns,
            width=350,
            height=160,
            editable=True,
            selectable=True,  # 关键修复点
            reorderable=False,
            row_height=40,
            autosize_mode="none",
            header_row=True
        )
    )

def create_readonly_table(source, title_text):
    """修复质心表格显示问题"""
    color_template = """
    <div style="background:<%= value %>; 
                width: 24px; 
                height: 24px;
                border-radius: 4px;
                border: 1px solid #666">
    </div>
    """
    
    columns = [
        TableColumn(
            field="color_hex", 
            title="颜色",
            width=70,
            formatter=HTMLTemplateFormatter(template=color_template)
        ),
        TableColumn(
            field="x", 
            title="X坐标",
            formatter=NumberFormatter(format="0.000"),
            width=110
        ),
        TableColumn(
            field="y",  # 添加Y坐标显示
            title="Y坐标",
            formatter=NumberFormatter(format="0.000"),
            width=110
        )
    ]
    
    return column(
        Div(text=f"<b style='color:#2C3E50'>{title_text}</b>", 
            styles={'margin-bottom': '10px'}),
        DataTable(
            source=source,
            columns=columns,
            width=350,
            height=80,
            editable=False,
            autosize_mode="none"
        )
    )

# 保持原有V2.0代码不变，仅添加以下验证函数
def validate_k_input(input_str, max_value):
    """验证k值输入有效性"""
    try:
        k = int(input_str)
        if 1 <= k < max_value:
            return True, k
        return False, None
    except ValueError:
        return False, None